package workcount;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;

/**
 * 用于指定目录下，指定扩展名的文件
 *
 * */
public class Searcher implements FileVisitor {

    private final PathMatcher matcher;
    private ArrayList<String> filePaths = new ArrayList<>();

    public Searcher(String ext) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:"+ext);
    }

    public void judgeFile(Path file) throws IOException{
        Path name = file.getFileName();
        if(name!=null && matcher.matches(name)){
            filePaths.add(file.toRealPath().toString());
        }
    }

    @Override
    public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
        judgeFile((Path)file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    /**
     *返回满足条件的文件列表
     * */
    public ArrayList<String> getFilePaths(){
        return filePaths;
    }
}
